# -*- coding: utf-8 -*-
import email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import poplib
import time
import datetime
import smtplib

from config import config
from logger import logger


class EmailOperation():
    def __init__(self):
        self.to_reply = []
        """:type : list[(str, datetime)]"""
        self.start_time = datetime.datetime.now()
        pass

    @staticmethod
    def send(mail_to, subject, message):
        server = smtplib.SMTP_SSL(host=config.smtp.address, port=config.smtp.port)
        server.login(config.email, config.password)

        msg = MIMEMultipart()
        msg['From'] = config.email
        msg['To'] = ", ".join(mail_to)
        msg['Subject'] = subject

        # 添加邮件内容
        txt = MIMEText(message)
        msg.attach(txt)

        k = msg.as_string()

        server.sendmail(config.email, mail_to, k)
        server.quit()

    def receive(self):
        server = poplib.POP3_SSL(host=config.pop.address, port=config.pop.port, timeout=5)
        server.user(config.email)
        server.pass_(config.password)

        ret = server.list()
        mail_count = len(ret[1])

        if mail_count == 0:
            logger.info('no new mail, exit this time.')
            return

        for i in range(mail_count, 1, -1):
            response, messages, octet = server.retr(i)
            mail = email.message_from_bytes('\n'.encode('utf-8').join(messages))
            subject = email.header.decode_header(mail.get('subject'))

            if type(subject[0][0]) in (type(b' '),) and subject[0][0] is not None and subject[0][1] is not None:
                subject = subject[0][0].decode(subject[0][1])
            else:
                subject = subject[0][0]

            # 获取发件人邮箱
            mail_from = email.utils.parseaddr(mail['From'])[1]

            # 获取发件时间
            mail_time = email.utils.parsedate(mail['Date'])
            if mail_time is not None:
                mail_time = datetime.datetime.fromtimestamp(time.mktime(mail_time))

            if not self.filter_mail(subject, mail_from, mail_time):
                break

        server.quit()

    def filter_mail(self, subject, mail_from, mail_time):
        """
        过滤邮件（只检查时间为一个小时内收到的邮件，标题包含：“GetIP”的邮件，不区分大小写）
        :param subject:
        :type subject: str
        :param mail_from:
        :type mail_from: str
        :param mail_date:
        :type mail_date: date
        :return: True: 继续读取下一封邮件，False: 终止邮件读取
        :rtype: bool
        """

        # logger.debug('%s    %-40s %s' % (mail_time, mail_from, subject))

        if (self.start_time - mail_time).total_seconds() <= 3600:
            if 'getip' in subject.lower():
                self.to_reply.append((mail_from, mail_time))
            return True

        return False


operation = EmailOperation()
